<?php
namespace control;
/*
*车间考勤表类
*/

class workshopClockClass extends adIndexClass
{
    private const page = 'workshopClock';
    private const table = 'workshop_clock';
    private const tableMx = 'workshop_clock_detail';
    private const tableStaff = 'workshop_clock_staff';
    private const title = '车间考勤表';
    public array $weekArray = array("日", "一", "二", "三", "四", "五", "六");

    /**
     * 字段初始化
     */
    public function fieldInit($fun): array
    {
        switch ($fun) {
            default:
                $tr = [
                    'orderNo'          => [
                        'name'  => "单据编号",
                        'width' => 200,
                        'sort' => 1,
                    ],
                    'workshop'  => [
                        'name'  => '车间',
                        'width' => 200,
                    ],
                    'teamId'         => [
                        'name'  => '班组',
                        'width' => 200,
                    ],
                    'month'          => [
                        'name'  => '月份',
                        'width' => 200,
                        'sort' => 1,
                    ],
                    'hour'          => [
                        'name'  => '工时合计',
                        'width' => 200,
                    ],
                    'state'          => [
                        'name'  => '状态',
                        'width' => 200,
                    ],
                    'stid'          => [
                        'name'  => '制表人',
                        'width' => 150,
                    ],
                    'updateTime'          => [
                        'name'  => '更新日期',
                        'width' => 200,
                        'sort' => 1,
                    ]
                ];
        }
        return $tr;
    }

    /*列表页-查询条件*/
    public function homeOptions($isAsync = true)
    {
        //生成查询表单
        $html = $this->tableShow([
            [
                [
                    "单据编号" => text(array("name" => "orderNo")),
                    "车间"   => selectMultiple(array("name" => "workshop", "table" => "product_line", 'field' => 'distinct(workshop) as workshop', 'sqlField' => 'workshop','where'=>"coid = '".self::$coid."'", 'sqlId' => 'workshop', 'class' => 'width200')),
                    '班组' => selectMultiple(array("name" => "teamId", "table" => "team",'where'=>"coid = '".self::$coid."'",   'sqlField' => 'name', 'sqlId' => 'id', 'class' => 'width200')),
                ],
                [
                    "月份" => text(array("name" => "createTime", 'laydate' => ['type' => 'date', 'range' => '~'])),
                    "状态" => select(["name" => "state", 'option' => ['草稿', '待确认', '已确认']]),
                ]
            ]
        ],1);
        //返回
        if (!$isAsync) {
            return $html;
        } else {
            return json_encode(['html' => $html], 320);
        }
    }

    /*列表-查询条件*/
    public function home()
    {
        $html = $this->homeOptions(false);
        //控件
        $button = "";
        $url = root . "control/adIndex.html?cla=" . self::page;
        if ($this->power(self::page, "edit")) {
            $button .= "<span onclick=\"layer('" . self::page . "','edit',{id:'" . self::getId() . "'})\" class='spanButton'>新增</span>\n";
        }
        if ($this->power(self::page, "del")) {
            $button .= "<span class='spanButton' onclick=\"layer('{$this->get('cla')}', 'operate', {'act': 'del'})\">删除</span>\n";
        }
        //返回
        return $this->homeFun($this->search($html, layout: 'pop', toolButton: $button));
    }

    /*客户列表-查询结果*/
    public function homeSearch()
    {
        //like查询数组
        $like = array(
            "orderNo" => $this->post('orderNo'),//单据编号
        );
        //全等查询数组
        $equal = array(
            "workshop" => $this->post('workshop'),//车间
            "teamId" => $this->post('teamId'),
            "state" => $this->post('state'),
            'coid' => self::$coid
        );
        $and = "";
        if ($this->post('createTime')) {
            $and .= self::timeComparison($this->post('createTime'), 'month', 'month');
        }
        //排序
        $orderBy = $this->listSort(array(
            "search"  => $this->post('list_sort_key') ?: 'month desc,time',
            "sort" => $this->post('list_sort') ?: "desc",
            "array"   => array(),
        ));
        //获取查询结果
        $where = search(array("like" => $like, "=" => $equal)) . $and;
        $page = $this->page(array("table" => self::table, "where" => $where, "order" => $orderBy['orderBy']));
        //获取自定义字段参数
        $installSearch = $this->installSearch();
        $body          = [];
        //表格控件区
        $liButton = array(
            $this->checkAll("listForm", "listId")
        );
        //获取记录
        $url = root . "control/adIndex.html?cla=" . self::page;
        foreach ($page['array'] as $array) {
            //列表控件
            $dominate = array(
                "box" => array("name" => "listId", "value" => $array['id']),
                "detail" => array("title" => self::title . "详情", "click" => "newIframe('" . self::title . "详情','" . $url . "&fun=detail&id=" . $array['id'] . "')"),
            );
            $liButton[] = $this->dominate($dominate);
            //本行初始化
            $row = [];
            foreach ($installSearch['key'] as $key) {
                switch ($key) {
                    case 'teamId':
                        $row[] = $this->teamName($array['teamId']);
                        break;
                    case 'hour':
                        $hour = find(array('table' => self::tableMx, "where" => "orderId = '$array[id]'", 'sum' => "hour"));
                        $row[] = $hour;
                        break;
                    case 'stid':
                        $row[] = self::findStaff($array['stid']);
                        break;
                    default:
                        $row[] = isset($array[$key]) && $array[$key] ? $array[$key] : '';
                }
            }
            $body[] = $row;
        }
        $totalQuery = find([
            'table'  => self::tableMx,
            'single' => " orderId in (select id from ".self::table." where 1=1 {$where}) ",
            'field'  => "ifnull(sum(hour),0) as hour",
        ]);
        $total    = [
            'hour'        => self::lostZero($totalQuery['hour'], 'numPrecision'),
        ];
        //生成页面
        $li = $this->li(array(
            "body" => $body,
            "install" => $installSearch,
            "button" => array("html" => $liButton),
            "orderBySign" => $orderBy,
            "page" => $page['para'],
            "total"       => $total,
        ));
        //返回
        $json['html'] = $page['hint'] . "<form name='listForm'>" . $li . "</form>" . $page['button'] . clear;
        return json_encode($json, 320);
    }

    /**
     * 获取班组名称
     * @param $teamIds
     * @return string
     */
    public function teamName($teamIds): string
    {
        $ids = explode(',', $teamIds);
        $teamName = '';
        if (is_array($ids)) {
            foreach ($ids as $teamId) {
                $team = query('team', "id = '$teamId'");
                if (!empty($team['id'])) {
                    $teamName .= $team['name'] . ',';
                }
            }
        }
        return rtrim($teamName, ',');
    }

    /**
     * 编辑页
     * @return string
     */
    public function edit(): string
    {
        $info = query(self::table, " id = '" . $this->post('id') . "' ");
        $html = $this->layerEdit(array("table" => array(
            array(
                must . "月份：" => text(array('name' => 'month', 'value' => $info['month'] ?: date('Y-m'), 'laydate' => ['type' => 'month'])),
            ),
            array(
                must . "车间：" => selectMultiple(array("name" => "workshop", "title" => "车间", 'value' => $info['workshop'], "table" => "product_line", 'where' => "state = '启用' and coid = '" . self::$coid . "'", 'field' => 'distinct(workshop) as workshop', 'sqlField' => 'workshop', 'sqlId' => 'workshop')),
            ),
            array(
                must . "班组：" => selectMultiple(array("name" => "teamId[]", 'value' => $info['teamId'], 'multiple' => true, "title" => "班组", 'where' => "state = '启用' and coid = '" . self::$coid . "'", "table" => "team", 'sqlField' => 'name', 'sqlId' => 'id'))
            ),
            array(
                "备注：" => textarea(array('name' => 'text', 'value' => $info['text'], 'class' => 'textarea')),
            ),
        )));
        //返回
        return $this->layer(array("title" => "编辑", 'winFix' => true, "height" => 400, "width" => 900, "html" => $html));
    }

    public function editEdit()
    {
        $id = $this->post('id') ?: self::getId();
        $field = [
            'month' => $this->post('month'),
            'workshop' => $this->post('workshop'),
            'teamId' => $this->post('teamId') ? implode(',', $this->post('teamId')) : '',
            'text' => $this->post('text'),
        ];
        $annotation = [
            'month' => '月份',
            'workshop' => '车间',
            'teamId' => '班组',
        ];
        $rules = [
            'month' => 'required',
            'workshop' => 'required',
            'teamId' => 'required',
        ];
        // 校验是否符合规则
        $vt = new \verify();
        $result = $vt->setAliases($annotation)->validate($field, $rules)->isOk();
        if ($result === false) {
            $json['warn'] = $vt->getErrs()[0];  // 多个规则提示最前面一条
            goto resp;
        }
        //判断
        if (!$this->power(self::page, "edit")) {
            $json['warn'] = "你没有编辑" . self::title . "的权限";
        } elseif (static::total(array('table' => self::table, 'where' => " month = '$field[month]' and coid = '" . self::$coid . "' and workshop = '$field[workshop]' and teamId like '%" . $field['teamId'] . "%' and id !='$id'")) > 0) {
            $json['warn'] = "已存在当前月份此车间相同的班组";
        } else {
            $where = " id = '$id' ";
            $info = query(self::table, $where);
            $this->startTrans();
            if (!$info['id']) {
                $userNo = codeTemplateClass::generateCode(self::page,[
                    'prefix' => 'CJKQ' . date('Ymd'),
                    'table' => self::table,
                    'field' => 'orderNo',
                    'where' => '',
                ],$field);
                $field = array_merge($field, [
                    'id' => $id,
                    'coid' => self::$coid,
                    'orderNo' => $userNo,
                    'stid' => $this->control['stid'],
                    'state' => '草稿',
                ]);
                $json['warn'] = static::insert(["table" => self::table, "field" => $field]);
            } else {
                $json['warn'] = static::update([
                    "table" => self::table,
                    "field" => $field,
                    "where" => $where
                ]);
            }
            foreach ($this->post('teamId') as $teamId) {
                $teamMx = find(array('table' => 'team_detail', 'where' => "orderId = '$teamId' order by list asc"));
                foreach ($teamMx['array'] as $array) {
                    $warn = static::insert(array(
                        'table' => self::tableStaff,
                        'field' => [
                            'id' => self::getId(),
                            'stid' => $array['stid'],
                            'orderId' => $id,
                            'teamId' => $teamId,
                            'coid' => self::$coid
                        ]
                    ));
                    if ($warn != '新增成功') {
                        $json['warn'] = $warn;
                        break;
                    }
                }
            }

            if (in_array($json['warn'], ["新增成功", "更新成功"])) {
                $this->commitTrans();
                //添加日志
                $type = mb_substr($json['warn'], 0, 2, 'utf-8');
                $text = $this->control['name'] . $type . "了" . self::title . " id：【" . $id . '】，车间：' . $field['workshop'] . ',月份：' . $field['month'];
                $this->logText(["type" => self::page, "text" => $text]);
                //返回
                $_SESSION['warn'] = $json['warn'];
                $json['warn'] = 2;
            } else {
                $this->rollback();
            }
        }

        resp:
        return json_encode($json, 320);
    }


    public function refreshStaff(): bool|string
    {
        $html = $this->layerEdit(array("table" => array(
            array(
                must . "提示：" => "是否更新考勤表中员工？",
            ),
        )));
        //返回
        return $this->layer(array("title" => "更新员工", "height" => 200, "html" => $html));
    }

    public function refreshStaffEdit()
    {
        $info = query(self::table, " id = '{$this->post('id')}'");
        $teamIds = explode(',',$info['teamId']);
        foreach ($teamIds as $teamId) {
            $teamMx = find(array('table' => 'team_detail', 'where' => "orderId = '$teamId' and stid not in (select stid from ".self::tableStaff." where orderId = '$info[id]' and teamId = '$teamId') order by list asc"));
            foreach ($teamMx['array'] as $array) {
                static::insert(array(
                    'table' => self::tableStaff,
                    'field' => [
                        'id' => self::getId(),
                        'stid' => $array['stid'],
                        'orderId' => $info['id'],
                        'teamId' => $teamId,
                        'coid' => self::$coid
                    ]
                ));
            }
            delete(array('table'=>self::tableStaff,'where'=>"teamId = '$teamId' and orderId = '$info[id]' and stid not in (select stid from team_detail where orderId = '$teamId')"));
        }
        $json['warn'] = 2;
        $text = $this->control['name'] ."更新了" . self::title . " id：【" . $info['id'] . '】，车间：' . $info['workshop'] . ',月份：' . $info['month'];
        $this->logText(["type" => self::page, "text" => $text]);
        return json_encode($json,320);
    }

    /*详情页*/
    public function detail(): string
    {
        $info = query(self::table, " id = '{$this->get('id')}'");
        if (empty($info['id'])) {
            $html = '未找到此' . self::title;
        } else {
            //菜单
            $data = array(
                "id" => $info['id'],
                "title" => self::title . '详情',
                'menu' => [
                    'edit' => '基本信息',
                ]
            );
            static::rSet(self::$stid . self::page . 'Id', $info['id']);


            $button = [];
            if ($info['state'] == '草稿') {
                //按钮
                $button[] = [
                    "name" => "提交",
                    "type" => "弹出层",
                    "cla" => $this->get('cla'),
                    "fun" => "operate",
                    "post" => ["act" => 'commit', "id" => $info['id']],
                    'style' => 'li-btn-blue-bg',
                ];
            }
            if ($info['state'] != '已确认') {
                if ($this->power(self::page, "edit")) {
                    //按钮
                    $button[] = [
                        "name" => "更新员工",
                        "type" => "点击事件",
                        "title" => self::page,
                        "fun" => "layer('" . self::page . "','refreshStaff',{id:'" . $info['id'] . "'})",

                    ];
                }

                if ($this->power(self::page, "del")) {
                    //按钮
                    $button[] = [
                        "name" => "删除",
                        "type" => "弹出层",
                        "cla" => $this->get('cla'),
                        "fun" => "operate",
                        "post" => ["act" => 'del', "id" => $info['id']],
                    ];
                }
            }

            if ($this->power(self::page, "confirm") && $info['state'] == '待确认') {
                $button[] = [
                    "name" => "确认",
                    "type" => "弹出层",
                    "cla" => $this->get('cla'),
                    "fun" => "operate",
                    "post" => ["act" => 'confirm', "id" => $info['id']],
                    'style' => 'li-btn-blue-bg',
                ];
            }
            if ($this->power(self::page, "cancel") && $info['state'] == '已确认') {
                $button[] = [
                    "name" => "撤回",
                    "type" => "弹出层",
                    "cla" => $this->get('cla'),
                    "fun" => "operate",
                    "post" => ["act" => 'cancel', "id" => $info['id']],
                ];
            }
            //操作记录
            $button[] = self::operateLogBut($info['id']);

            $mxButton = '';//明细按钮
            if ($this->power(self::page, "import")) {
                $mxButton .="<span class='smallButton' onclick=\"layer('importTemplate','importFrame',{cla:'".self::page."'})\">导入</span>";
            }
            if ($this->power(self::page, "export")) {
                $mxButton .= "<a href='" . root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=exportData'><span class='smallButton'>导出</span></a>\n";
            }
            $mxButton .= "<span class='smallButton' onclick=\"layer('" . self::page . "','selectDate',{id:'$info[id]'})\">获取最新打卡记录</span>";


            //生成表单
            $data['button'] = $this->tableShowButton($button);
            $data['html'] = $this->tableShow(array(
                "基本信息" => array(
                    array(
                        "车间" => $info['workshop'],
                        "班组" => $this->teamName($info['teamId']),
                        "制表人" => self::findStaff($info['stid']),
                        "单据编号" => $info['orderNo'],
                    ),
                    array(
                        "创建时间" => $info['time'],
                        "更新时间" => $info['updateTime'],
                        "确认时间" => $info['confirmTime'],
                        "确认人" => self::findStaff($info['checkId']),
                    ),
                    array(
                        "状态" => $info['state']
                    ),
                ),
            ));
            $data['html'] .= $this->detailList([
                'title' => '考勤详情',
                'button' => $mxButton,
                'html' => "<div class='purchaseMx'><form name='detailForm'>" . hidden(array('name' => 'id', 'value' => $info['id'])) . $this->calendar($info['month'], $info['id']) . "</form></div><div style='margin-top: 5px'>" . must . "非草稿状态下可在计件工资中生效</div>",
            ]);
            //生成页面
            $html = $this->tab($data);
        }
        return $html;
    }

    public function calendar($month, $id): string
    {
        $info = query(self::table, "id = '" . $id . "'");
        //总天数
        $days = date('t', strtotime($month));
        $date = date('Y-m-01', strtotime($month));
        $dayHtml = "<tr class='no-edit'><td style='min-width: 50px'></td>";
        $weekHtml = "<tr class='no-edit'><td></td>";
        $lineHtml = "<tr class='no-edit'><td></td>";
        for ($i = 1; $i <= $days; $i++) {
            $dayHtml .= "<td>{$i}</td>";
            //判断当前日期是星期几
            $weekHtml .= "<td>" . $this->weekArray[date("w", strtotime(date('Y-m', strtotime($date)) . '-' . $i))] . "</td>";
            //间隔
            $lineHtml .= "<td>&nbsp;</td>";
        }
        $dayHtml .= "</tr>";
        $weekHtml .= "</tr>";
        $lineHtml .= "</tr>";
        $memberArr = find(array('table' => self::tableStaff, 'where' => "orderId = '$info[id]' order by list asc"));
        $peopleHtml = '';
        //合计数组
        $totalArr = [];
        if (is_array($memberArr['array'])) {
            foreach ($memberArr['array'] as $array) {
                $staff = query('staff', " stid = '$array[stid]'");
                $team = query('team', "id = '$array[teamId]'");
                $peopleHtml .= "<tr class='click-line'><td>{$team['name']}-{$staff['name']}</td>";
                for ($i = 1; $i <= $days; $i++) {
                    $toDay = date('Y-m', strtotime($date)) . '-' . sprintf("%02d", $i);//当前日期
                    $mx = query(self::tableMx, "orderId = '$info[id]' and recordDate = '$toDay' and stid = '$array[stid]'");
                    $word = $mx['hour'];
                    $edit = $info['state'] == '已确认' ? '' : 'contenteditable';
                    $class = '';
                    $peopleHtml .= "<td class='{$class}'  {$edit} onblur='set_hour(this)' data-date='{$toDay}' data-stid='$array[stid]'>{$word}</td>";
                    $totalArr[$toDay] = $totalArr[$toDay] ?? 0;
                    $totalArr[$toDay] += (float)$mx['hour'];
                }
                $peopleHtml .= "</tr>";
            }
        }
        /******总计*****************/
        $totalHtml = "<tr><td>合计</td>";
        for ($i = 1; $i <= $days; $i++) {
            $toDay = date('Y-m', strtotime($date)) . '-' . sprintf("%02d", $i);//当前日期
            $totalArr[$toDay] = $totalArr[$toDay] ?? '';
            $totalHtml .= "<td>{$totalArr[$toDay]}</td>";
        }
        $totalHtml .= "</tr>";


        return <<<eof
<div class="calendarBody">
<div class="calendarTitle"><span class="calendar-date">{$month}</span><input type="hidden" name="toDate" value="$date"></div>
<div class="calendarContent">
<input name="id" type="hidden" value="{$info['id']}">
<table class="dayTable">
{$dayHtml}
{$weekHtml}
{$peopleHtml}
{$lineHtml}
{$totalHtml}
</table>
</div>
</div>

<script>
  function set_hour(e){
           let id = $("[name = 'id']").val();
           let hour = $(e).text();
           let date = $(e).data('date');
           let stid = $(e).data('stid');
           $.post(root+'control/adIndex.html?cla={$this->get('cla')}&fun=setHour',{stid:stid,id:id,date:date,hour:hour},function (res){
              if (res.warn !=2){
                msg(res.warn,'error')
              }
           },'json')
       }
</script>

<style>
.calendarContent{
 margin: 0 auto;
 padding-bottom: 20px
}

.calendar-date{
font-weight: bold;font-size: 17px
}
.calendarBody{
 width: 95%;
}
.calendarTitle{
 width: 100%;
 height: 50px;
 text-align: center;
 line-height: 50px
}
.click-line td{
 cursor: pointer;
}

.dayTable{
border-collapse: collapse;
    border-spacing: 0;
}
.dayTable td {
    border: 1px solid rgb(230, 230, 230);
    word-break: break-all;
}
.rest-day{
  background-color: #F2F2F2;
  color: gray;
}
.no-edit{
background-color: #F8F8F8
}

</style>


eof;
    }


    /**
     * 确认
     */
    public function confirmEdit()
    {
        $id = $this->post('id');
        $info = query(self::table, " id = '$id'");
        $field = [
            'state' => '已确认',
            'checkId' => self::$stid,
            'confirmTime' => $this->time
        ];

        if (!$this->power(self::page, 'confirm')) {
            $json['warn'] = '你还没有确认权限';
        } elseif (empty($info['id'])) {
            $json['warn'] = '未找到此' . self::title;
        } elseif ($info['state'] != '待确认') {
            $json['warn'] = '此' . self::title . '不是待确认状态，不能确认';
        } else {
            $json['warn'] = static::update(array(
                "table" => self::table,
                "field" => $field,
                "where" => "id = '$info[id]'",
            ));
            if (in_array($json['warn'], ["新增成功", "更新成功"])) {
                //生成出库单
                auditingFollow(array(
                    "type" => "车间考勤",
                    "typeId" => $info['id'],
                    "text" => "【{$this->control['name']}】确认",
                    'job' => self::findStaffDepartment(self::$stid) . '-' . $this->controlJob['name'],
                    'staffName' => $this->control['name']
                ));
                //添加日志
                $type = mb_substr($json['warn'], 0, 2, 'utf-8');
                $text = $this->control['name'] . $type . "了" . self::title . "id：【" . $id . '】';
                $this->logText(["type" => self::page, "text" => $text]);
                //返回
                $_SESSION['warn'] = '确认成功';
                $json['warn'] = 2;
                $json['href'] = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=detail&id=" . $info['id'];
            }
        }
        resp:
        return json_encode($json, 320);
    }

    /**
     * 撤回
     */
    public function cancelEdit()
    {
        $id = $this->post('id');
        $info = query(self::table, " id = '$id'");
        $field = [
            'state' => '草稿',
            'checkId' => '',
            'confirmTime' => ''
        ];
        if (!$this->power(self::page, 'cancel')) {
            $json['warn'] = '你还没有撤回权限';
        } elseif (empty($info['id'])) {
            $json['warn'] = '未找到此车间考勤';
        } elseif ($info['state'] != '已确认') {
            $json['warn'] = '此车间考勤不是已确认状态，无需撤回';
        }/* elseif (static::total(array('table' => 'inventory', "where" => "sourceId = '$info[id]' and coid = '" . self::$coid . "' and state in ('部分出库','已出库')")) > 0) {
            $json['warn'] = '此车间考勤已存在有出库的单据，不能撤回';
        } */ else {
            $json['warn'] = update(array(
                "table" => self::table,
                "field" => $field,
                "where" => "id = '$info[id]'",
            ));
            if (in_array($json['warn'], ["新增成功", "更新成功"])) {
                auditingFollow(array(
                    "type" => "车间考勤",
                    "typeId" => $info['id'],
                    "text" => "【{$this->control['name']}】撤回",
                    'job' => self::findStaffDepartment(self::$stid) . '-' . $this->controlJob['name'],
                    'staffName' => $this->control['name']
                ));
                //添加日志
                $type = mb_substr($json['warn'], 0, 2, 'utf-8');
                $text = $this->control['name'] . $type . "了" . self::title . "id：【" . $id . '】';
                $this->logText(["type" => self::page, "text" => $text]);
                //返回
                $_SESSION['warn'] = '撤回成功';
                $json['warn'] = 2;
                $json['href'] = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=detail&id=" . $info['id'];
            }
        }
        resp:
        return json_encode($json, 320);
    }

    /**
     * 提交
     */
    public function commitEdit()
    {
        $id = $this->post('id');
        $info = query(self::table, " id = '$id'");
        $field = [
            'state' => '待确认',
        ];
        if (!$this->power(self::page, 'edit')) {
            $json['warn'] = '你还没有编辑权限';
        } elseif (empty($info['id'])) {
            $json['warn'] = '未找到此车间考勤';
        } elseif ($info['state'] != '草稿') {
            $json['warn'] = '此车间考勤不是草稿状态，不能提交';
        } else {
            $json['warn'] = update(array(
                "table" => self::table,
                "field" => $field,
                "where" => "id = '$info[id]'",
            ));
            if (in_array($json['warn'], ["新增成功", "更新成功"])) {
                auditingFollow(array(
                    "type" => "车间考勤",
                    "typeId" => $info['id'],
                    "text" => "【{$this->control['name']}】提交",
                    'job' => self::findStaffDepartment(self::$stid) . '-' . $this->controlJob['name'],
                    'staffName' => $this->control['name']
                ));
                //添加日志
                $type = mb_substr($json['warn'], 0, 2, 'utf-8');
                $text = $this->control['name'] . $type . "了" . self::title . "id：【" . $id . '】';
                $this->logText(["type" => self::page, "text" => $text]);
                //返回
                $_SESSION['warn'] = '提交成功';
                $json['warn'] = 2;
                $json['href'] = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=detail&id=" . $info['id'];
            }
        }
        resp:
        return json_encode($json, 320);
    }


    /**
     * 编辑考勤小时数
     */
    public function setHour(): bool|string
    {
        $field = array(
            'hour' => $this->post('hour'),
            'recordDate' => $this->post('date'),
            'stid' => $this->post('stid'),
            'orderId' => $this->post('id'),
        );
        $annotation = [
            'recordDate' => '日期',
            'stid' => '员工ID',
            'orderId' => '考勤表ID',
        ];
        $rules = [
            'recordDate' => 'required',
            'stid' => 'required',
            'orderId' => 'required',
        ];
        // 校验是否符合规则
        $vt = new \verify();
        $result = $vt->setAliases($annotation)->validate($field, $rules)->isOk();
        if ($result === false) {
            $json['warn'] = $vt->getErrs()[0];  // 多个规则提示最前面一条
            goto resp;
        }
        $info = query(self::table, "id = '$field[orderId]'");
        if (!$this->power(self::page, "edit")) {
            $json['warn'] = "你没有编辑" . self::title . "的权限";
        } elseif (!empty($field['hour']) && preg_match(checkPrice, $field['hour']) == 0) {
            $json['warn'] = '格式错误';
        } elseif ($info['state'] == '已确认') {
            $json['warn'] = '此考勤表已确认，不能修改';
        } else {
            $mx = query(self::tableMx, "recordDate = '$field[recordDate]' and stid = '$field[stid]' and orderId = '$info[id]'");
            if (empty($mx['id'])) {
                $field = array_merge($field, [
                    'id' => self::getId(),
                    'coid' => self::$coid,
                ]);
                $json['warn'] = static::insert(array(
                    'table' => self::tableMx,
                    'field' => $field
                ));
            } else {
                $json['warn'] = static::update([
                    "table" => self::tableMx,
                    "field" => $field,
                    "where" => "id = '$mx[id]'"
                ]);
            }
            if (in_array($json['warn'], ["新增成功", "更新成功"])) {
                $staff = query('staff', "stid = '$field[stid]'");
                //添加日志
                $type = mb_substr($json['warn'], 0, 2, 'utf-8');
                $text = $this->control['name'] . $type . "了员工【" . $staff['name'] . '】在车间【' . $info['workshop'] . '】，日期【' . $field['recordDate'] . '】的工时';
                $this->logText(["type" => self::page, "text" => $text]);
                //返回
                $json['warn'] = 2;
            }
        }
        resp:
        return json_encode($json, 320);
    }

    /**
     * 导出
     */
    public function exportData()
    {
        if (!$this->power(self::page, 'export')) {
            $_SESSION['warn'] = '你还没有导出的权限';
        } else {
            $data = [];
            $id = static::rGet(self::$stid . self::page . 'Id');
            $info = query(self::table, "id = '$id'");
            $month = $info['month'];
            $date = date('Y-m-01', strtotime($month));
            $days = date('t', strtotime($month));
            $dayTr[] = '';
            $weekTr[] = '';
            $lineTr[] = '';
            for ($i = 1; $i <= $days; $i++) {
                $dayTr[] = $i;
                $weekTr[] = $this->weekArray[date("w", strtotime(date('Y-m', strtotime($date)) . '-' . $i))];
                $lineTr[] = '';
            }
            $data[] = $weekTr;
            $memberArr = find(array('table' => self::tableStaff, 'where' => "orderId = '$info[id]' order by list asc"));
            //合计数组
            $totalArr = [];
            if (is_array($memberArr['array'])) {
                foreach ($memberArr['array'] as $array) {
                    $staff = query('staff', " stid = '$array[stid]'");
                    $team = query('team', " id = '$array[teamId]'");
                    $temp = [];
                    $temp[] = $team['name'] . '-' . $staff['name'];
                    for ($i = 1; $i <= $days; $i++) {
                        $toDay = date('Y-m', strtotime($date)) . '-' . sprintf("%02d", $i);//当前日期
                        $mx = query(self::tableMx, "orderId = '$info[id]' and recordDate = '$toDay' and stid = '$array[stid]'");
                        $temp[] = $mx['hour'];
                        $totalArr[$toDay] = $totalArr[$toDay] ?? 0;
                        $totalArr[$toDay] += (float)$mx['hour'];
                    }
                    $data[] = $temp;
                }
            }
            $data[] = $lineTr;
            /******总计*****************/
            unset($temp);
            $temp[] = '合计';
            for ($i = 1; $i <= $days; $i++) {
                $toDay = date('Y-m', strtotime($date)) . '-' . sprintf("%02d", $i);//当前日期
                $temp[] = $totalArr[$toDay];
            }
            $data[] = $temp;
            $text = $this->control['name'] . "导出了【{$month}】月份【{$info['workshop']}】的考勤表";
            $this->logText(["type" => self::page, "text" => $text]);
            $this->excelOut($dayTr, $data, "【{$month}】月份【{$info['workshop']}】的考勤表.xlsx");
        }
        header("Location:" . getenv("HTTP_REFERER"));
        exit(0);
    }

    /**
     * 下载模板
     */
    public function downloadModel()
    {
        $templateId = $this->get('templateId');
        if (!$this->power(self::page, 'import')) {
            $_SESSION['warn'] = '你还没有导入的权限';
        }   else {
            $exampleData[] = ['YM202101010001', '雨木', '2022-01-01', 8];
            $excel    = $this->excelHead();
            $fileName = self::title.'导入模板-'.importTemplateClass::getName($templateId).'.xlsx';
            $filePath = $excel->fileName($fileName, 'sheet1');
            $format = new \Vtiful\Kernel\Format($filePath->getHandle());
            $templateField = importTemplateClass::templateField(self::page, 'importFieldInit', id:$templateId);
            $index         = 0;
            foreach ($templateField as $k => $array) {
                if ($array['display']){
                    $backgroundStyle=null;
                    if (importTemplateClass::getIsMustValue($this->importFieldInit(), $array['columnName'])){
                        //必填项判断
                        $backgroundStyle  = $format->background(
                            0xFFC04B
                        )->toResource();
                    }
                    $filePath->insertText(0, $index, $array['aliasName'],'',$backgroundStyle);
                    foreach ($exampleData as $y=>$example){
                        $exampleVal = match ($array['columnName']){
                            '员工编号'=>$example[0],
                            '员工姓名'=>$example[1],
                            '日期'=>$example[2],
                            '时长'=>$example[3],
                            default=>'',
                        };
                        $filePath->insertText($y+1, $index, $exampleVal);
                    }
                    $index++;
                }
            }
            $text = $this->control['name'] . "下载了车间考勤表导入模板";
            $this->logText(["type" => self::page, "text" => $text]);
            $this->excelOutPut($filePath,$fileName);
            exit(0);
        }
        header("Location:" . getenv("HTTP_REFERER"));
    }

    /*数据导入分析*/
    public function importData()
    {
        $templateId = $this->post('templateId');
        $id = static::rGet(self::$stid . self::page . 'Id');
        $info = query(self::table, "id = '$id'");
        if (!$this->power(self::page, 'edit')) {
            $json['warn'] = '你还没有编辑的权限';
        } elseif ($info['state'] == '已确认') {
            $json['warn'] = '此考勤表已确认，不能修改';
        }   else {
             $fomatArray = [];//导入数据格式同一为TYPE_STRING
            foreach ($this->importFieldInit() as $value){
                $fomatArray[] = \Vtiful\Kernel\Excel::TYPE_STRING;
            }
            $data = $this->importHead(format: $fomatArray);
            $x = 0;
            $text = '';
            $headArray = [];
            $row_list=0;
            foreach ($data as $i => $row) {
                $row_list++;
                if ($i==0){
                    $templateField = importTemplateClass::templateField(self::page, 'importFieldInit', id:$templateId);
                    $headArray = importTemplateClass::combinHead($templateField,$row);
                }
                if ($i > 0) {
                    $rowData = formSubArray($row);
                    //只接收模板中选中的字段的值
                    $cell = [];
                    foreach ($headArray as $index=>$headName){
                        $cell[$headName] = $rowData[$index]??'';
                    }
                    //初始化未被模板需要的字段的值
                    foreach ($this->importFieldInit() as $value){
                        $cell[$value['columnName']] = $cell[$value['columnName']]??'';
                    }
                    $staff = query('staff', "orderNo = '$cell[员工编号]'");
                    $field = [
                        'stid' => $staff['stid'],
                        "recordDate" => self::importDateFormat($cell['日期']),
                        "hour" => $cell['时长'],
                        'orderId' => $info['id'],
                    ];
                    $annotation = [
                        'orderId' => '车间考勤表ID',
                        'recordDate' => '日期',
                        'hour' => '工时',
                        'stid' => '员工',
                    ];
                    $rules = [
                        'orderId' => 'required',
                        'recordDate' => 'required|date',
                        'stid' => 'required',
                    ];
                    // 校验是否符合规则
                    $vt = new \verify();
                    $result = $vt->setAliases($annotation)->validate($field, $rules)->isOk();
                    if ($result === false) {
                        $text .= "第【{$row_list}】行：" . $vt->getErrs()[0] . "<br>";  // 多个规则提示最前面一条
                    } elseif ($info['month'] != date('Y-m', strtotime($field['recordDate']))) {
                        $text .= "第【{$row_list}】行：不是此车间考勤表月份的考勤<br>";
                    } elseif (!empty($field['hour']) && preg_match(checkPrice, $field['hour']) == 0) {
                        $text .= "第【{$row_list}】行：工时格式错误<br>";
                    } elseif (static::total(array('table' => self::tableStaff, 'where' => "stid = '$field[stid]'")) == 0) {
                        $text .= "第【{$row_list}】行：此考勤表中没有此员工<br>";
                    } else {
                        $mx = query(self::tableMx, "recordDate = '$field[recordDate]' and stid = '$field[stid]' and orderId = '$info[id]'");
                        if (empty($mx['id'])) {
                            $field = array_merge($field, [
                                'id' => self::getId(),
                                'coid' => self::$coid,
                            ]);
                            $json['warn'] = static::insert(array(
                                'table' => self::tableMx,
                                'field' => $field
                            ));
                        } else {
                            $json['warn'] = static::update([
                                "table" => self::tableMx,
                                "field" => $field,
                                "where" => "id = '$mx[id]'"
                            ]);
                        }

                        if (in_array($json['warn'], ["新增成功", "更新成功"])) {
                            $x++;
                            $text .= "第【{$row_list}】行导入成功<br>";
                        } else {
                            $text .= "第【{$row_list}】行导入失败：编辑失败<br>";
                        }
                    }
                }
            }
            $total = count($data)-1;
            $json['data'] = [
                'text'=>$text,
                'title'=>"您导入了{$total}条数据，成功{$x}条，失败".($total-$x)."条",
            ];
            $text = $this->control['name'] . '导入了文件：' . $_FILES['file']['name'] . '：' . $text;
            $this->logText(["type" => self::page, "text" => $text]);
            $json['warn'] = 2;
        }
        return json_encode($json,320);
    }

    // 操作中转
    public function operate()
    {
        $act = $this->post('act') ?? '';
        $pwd = false; // 需要密码
        $form = $power = $word = '';
        switch ($act) {
            case 'confirm':
                $act = 'confirm';
                $msg = '确认';
                $title = '是否已确认此' . self::title . '，确认后将不可修改？';
                $function = 'confirmEdit';
                $form = self::page . 'OperateForm, detailForm';
                $power = '';
                $word = true;
                break;
            case 'commit':
                $act = 'edit';
                $msg = '编辑';
                $title = '是否确认提交此' . self::title . '？';
                $function = 'commitEdit';
                $form = self::page . 'OperateForm, detailForm';
                $power = '';
                $word = true;
                break;
            case 'cancel':
                $act = 'cancel';
                $msg = '撤回';
                $title = '是否确认撤回此' . self::title . '？';
                $function = 'cancelEdit';
                $form = self::page . 'OperateForm, detailForm';
                $power = '';
                $word = true;
                break;
            default:
                $act = 'del';
                $msg = '删除' . self::title;
                $title = self::page . 'Delete';
                $function = 'delete';
                $form = self::page . 'OperateForm, listForm';
                $power = '';
                break;
        }
        if (!$this->power(self::page, $act)) {
            $_SESSION['warn'] = '你还没有' . $msg . '的权限';
            $json = [
                'warn' => 2,
                'href' => root . 'control/adIndex.html?cla=' . $this->get('cla') . '&fun=home',
            ];
        } else {
            return $this->confirm([
                'title' => $title,
                'function' => $function,
                'form' => $form,
                'power' => $power,
                'pwd' => $pwd,
                'word' => $word
            ]);
        }

        resp:
        return json_encode($json, 320);
    }


    /**
     * 删除
     * @return bool|string
     */
    public function delete()
    {
        $array = $this->post('listId') ?? $this->post('id');
        if (!$this->power(self::page, "del")) {
            $json['warn'] = "你没有删除的权限";
        } elseif (empty($array)) {
            $json['warn'] = "你一个数据都没有选择呢";
        } else {
            $text = "";
            $x = 0;
            $array = is_array($array) ? $array : [$array];
            foreach ($array as $id) {
                $info = query(self::table, " id = '$id' ");
                if ($info['state'] == '已确认') {
                    $warn = "已确认，暂不能删除";
                } else {
                    //删除待办事项
                    delete(array("table" => "auditing_follow", "where" => " typeId = '$id' "));
                    //最后删除基本参数
                    delete(array("table" => self::table, "where" => " id = '$id' "));
                    delete(array("table" => self::tableStaff, "where" => " orderId = '$id' "));
                    delete(array("table" => self::tableMx, "where" => " orderId = '$id' "));
                    //返回
                    $warn = "删除成功";
                    $x++;
                }
                $text .= self::title . "ID【" . $info['id'] . "】" . $warn . "。<br>";
            }
            //添加日志
            $text = $this->control['name'] . "删除了" . self::title . "，结果如下：<br>" . $text;
            $this->logText(array("type" => self::page, "text" => $text));
            $_SESSION['warn'] = "删除了" . $x . "个" . self::title . "，详情见系统日志。";
            $json['warn'] = 2;
            $json['href'] = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=home";
        }
        return json_encode($json, 320);
    }

    /**
     * 选择获取时间范围(7天内)
     */
    public function selectDate(): bool|string
    {
        $form = $this->get('cla') . ucwords($this->get('fun')) . "Form";
        //拼接表单
        $html = $this->layerEdit([
            "table" => [
                array(
                    must . "提示：" => "将获取起始日期7天内的打卡记录",
                ),
                array(
                    must . "起始日期：" => text(array("name" => "startDate", 'class' => 'width200', 'value' => date('Y-m-d', strtotime("-7 day")), "laydate" => array("type" => "date", 'max' => 0))).hidden(array("name"=>"id","value"=>$this->post('id'))),
                ),
            ],
        ]);
        //返回
        return $this->layer(array(
            "title" => "选择日期",
            "height" => 200,
            "width" => 600,
            "html" => $html,
            'button' => "<input onclick=\"subForm('" . $form . "','" . root . "control/adIndex.html?cla=" . self::page . "&fun=dingIn')\" type='button' class='button' value='确认提交'>",
        ));
    }
    /*将获取的钉钉考勤记录录入数据库*/
    public function dingIn()
    {
        $workSignCheckClass = new workSignCheckClass();
        $info = query(self::table, " id = '{$this->post('id')}'"); //车间考勤表
        $day = $workSignCheckClass->dingDay($this->post('startDate'));
        $result = $this->dingUser(array("id" => $info['id']));
        $x = 0;
        $pass = true;
        foreach ($result as $item) {
            $getSign = $workSignCheckClass->dingRead($item, $day);
            if (is_array($getSign['sign'])) {
                foreach ($getSign['sign'] as $array) {
                    $workSign = query("work_sign", " signId = '$array[id]' ");
                    $staff = query("staff", " dingtalkId = '$array[userId]' ");
                    $signDay = $workSign['signTime']?date("Y-m-d",strtotime($workSign['signTime'])):'';
                    if (empty($workSign['signId']) and $array['sourceType'] == "ATM") {
                        $userCheckTime = $array['userCheckTime'] / 1000;
                        $signDay = date("Y-m-d", $userCheckTime);//打卡日期
                        $signTime = date("H:i:s", $userCheckTime);//打卡时间
                        $array['userLatitude'] = $array['userLatitude']??'';
                        $array['userLongitude'] = $array['userLongitude']??'';
                        $type = match ($array['sourceType']) {
                            'USER' => '用户打卡',
                            'ATM' => '钉钉考勤机',
                            'DING_ATM' => '考勤机蓝牙打卡',
                            'BOSS' => '老板改签',
                            'APPROVE' => '审批系统',
                            'SYSTEM' => '考勤系统',
                            'AUTO_CHECK' => '自动打卡',
                            default => $array['sourceType']
                        };
                        insert(array(
                            "table" => "work_sign",
                            "field" => $field = array(
                                "jobId" => $staff['jobId'],
                                "stid" => $staff['stid'],
                                "dingtalkId" => $staff['dingtalkId'],
                                "signId" => $array['id'],
                                "signTime" => $signDay . " " . $signTime,
                                "type" => $type,
                                'latlng' => $array['userLatitude'] . ',' . $array['userLongitude']
                            ),
                        ));
                        $workSignCheckClass->updatePersonalSign($staff,$field);//更新每日个人考勤数据
                        $x++;
                    }
                    $work_sign_single = query('work_sign_single', "date = '$signDay' and stid = '$staff[stid]'");
                    $workshop_clock_detail = query(self::tableMx, "orderId = '$info[id]' and recordDate = '$signDay' and stid = '$staff[stid]'");
                    if (empty($workshop_clock_detail['id'])) {
                        $field = array(
                            'id' => self::getId(),
                            'coid' => self::$coid,
                            'hour' => $work_sign_single['workHour'],
                            'recordDate' => $signDay,
                            'stid' => $staff['stid'],
                            'orderId' => $info['id'],
                        );
                        $json['warn'] = static::insert(array(
                            'table' => self::tableMx,
                            'field' => $field
                        ));
                    }
                }
            } else {
                $pass = false;
                break;
            }
        }
        if ($pass) {
            //添加日志
            $json['warn'] = 2;
            $_SESSION['warn'] = "查询时间段" . $day['checkDateFrom'] . "-" . $day['checkDateTo'] . "，共录入了" . $x . "条考勤数据";
            $text = $this->control['name'] . $json['warn'];
        } else {
            $getSign['sign'] = $getSign['sign'] ?? '';
            $json['warn'] = "查询失败：" . $getSign['sign'];
            $text = $this->control['name'] . '查询时间段' . $day['checkDateFrom'] . "-" . $day['checkDateTo'] . "失败：" . $getSign['sign'];
        }

        $this->logText(array("type" => self::page, "text" => $text));
        //返回
        return json_encode($json, 320);
    }

    /*需要提取钉钉考勤的员工数组
     $data = array(
         "checkDateFrom" => "读取考勤数据的开始日期",
     );
     */
    public function dingUser($data): array
    {
        $result = [];
        $total = 50;
        for ($i = 0; $i < 100; $i++) {
            //查询试用，转正，停薪留职状态和已离职但离职时间晚于考勤查询时间的员工
            $startNum = $i * $total;
            $user = [];
            $memberArr = find(array('table' => self::tableStaff, 'where' => "orderId = '$data[id]' order by list asc limit $startNum,$total"));
            if (is_array($memberArr['array'])) {
                foreach ($memberArr['array'] as $array) {
                    $user[] = $array['stid'];
                }
            }
            $result[] = $user;
            if (count($user) < 50) {
                break;
            }
        }
        //返回
        return $result;
    }

    /**
     * 导入模板字段初始化
     * @return array[]
     */
    public function importFieldInit($classify=''): array
    {
        return match ($classify) {
            default=>  [
                [
                    'columnName'=>'员工编号',
                    'aliasName'=>'员工编号',
                    'isMust'=>true,
                ],
                [
                    'columnName'=>'员工姓名',
                    'aliasName'=>'员工姓名',
                    'isMust'=>false,
                ],
                [
                    'columnName'=>'日期',
                    'aliasName'=>'日期',
                    'isMust'=>true,
                ],
                [
                    'columnName'=>'时长',
                    'aliasName'=>'时长',
                    'isMust'=>false,
                ],
            ]
        };
    }
}
